package com.deprice4u_client;

import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.deprice4u_client.image_loader.ImageLoader;
import com.deprice4u_client.products_on_sale.SocialDataClass;

import android.app.Activity;
import android.content.SharedPreferences;
import android.database.CursorJoiner.Result;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

public class MakeNewRequestWithNaver extends Activity {
	private EditText etTitle;
	private ImageView ivNaverImage;
	private TextView tvLowPrice;
	private Button btnLeft;
	private Button btnRight;
	private EditText etDescription;
	private ImageLoader imageLoader;
	private int nArrayIndex;
	private String strUserID;
	
	private ArrayList<NaverSearchResult> items;
	
	private class NaverSearchResult {
		public String low_price;
		public String photo_url;
	}
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_request_with_naver);
		
		// Bind control
		etTitle = (EditText)this.findViewById(R.id.etTitle);
		tvLowPrice = (TextView)this.findViewById(R.id.tvLowPrice);
		btnLeft = (Button)this.findViewById(R.id.btnLeft);
		btnRight = (Button)this.findViewById(R.id.btnRight);
		ivNaverImage = (ImageView)this.findViewById(R.id.ivNaverImage);
		etDescription = (EditText)this.findViewById(R.id.etDescription);
		
		// Get User Info
        SharedPreferences settings = getSharedPreferences(Preference.PREFS_NAME, 0);
        strUserID = settings.getString(Preference.USER_ID, "null");
		
		// Init Internal 
		imageLoader = new ImageLoader(this);
		nArrayIndex = -1;
		
		// Init UI
		btnRight.setEnabled(false);
		btnRight.setFocusable(false);
		btnLeft.setEnabled(false);
		btnLeft.setFocusable(false);
	}
	
	public void onbtnLeftClick(View v){
		if(nArrayIndex > 0){
			nArrayIndex--;
			imageLoader.DisplayImage(items.get(nArrayIndex).photo_url, this.ivNaverImage);
			tvLowPrice.setText(items.get(nArrayIndex).low_price);
		}
		else{
			// TODO Need to modify
	    	Toast t = Toast.makeText(this, "First Search Result!" , Toast.LENGTH_SHORT);
	    	t.show();
		}
	}
	
	public void onbtnRightClick(View v){
		if(nArrayIndex+1 < items.size()){
			nArrayIndex++;
			imageLoader.DisplayImage(items.get(nArrayIndex).photo_url, this.ivNaverImage);
			tvLowPrice.setText(items.get(nArrayIndex).low_price);
		}
		else{
			// TODO Need to modify
	    	Toast t = Toast.makeText(this, "Last Search Result!" , Toast.LENGTH_SHORT);
	    	t.show();
		}
	}
	
	public void onbtnSubmitClick(View v){
		// Get data
    	String strTitle = this.etTitle.getText().toString();
    	String strDescription = this.etDescription.getText().toString();
    	String strLowPrice = this.tvLowPrice.getText().toString();
    	String strImageURL = items.get(this.nArrayIndex).photo_url;
    	
    	String key = sendPostData(strTitle, strUserID, strDescription, strLowPrice, strImageURL);
    	Log.i("SJ", key);
    	
    	// TODO Need to modify
    	Toast t = Toast.makeText(this, key, Toast.LENGTH_SHORT);
    	t.show();
	}
	
	public void onbtnSearchNaverClick(View v){
    	// Get data
    	String strTitle = this.etTitle.getText().toString();
    	items = searchNaver(strTitle);
    	
    	// Enable Button
    	btnRight.setEnabled(true);
		btnRight.setFocusable(true);
		btnLeft.setEnabled(true);
		btnLeft.setFocusable(true);
		
		if(items.size()>0){
			// Display default image
			this.nArrayIndex = 0;
			imageLoader.DisplayImage(items.get(0).photo_url, this.ivNaverImage);
			tvLowPrice.setText(items.get(0).low_price);
		}
		
    	// TODO Need to modify
    	Toast t = Toast.makeText(this, String.valueOf(items.size()) , Toast.LENGTH_SHORT);
    	t.show();
    }
	
	private String sendPostData(String strTitle, 
			String strUserID, 
			String strDescription, 
			String strLowPrice,
			String strImageURL){
		String strKey = null;
		URL queryURL=null; 
		StringBuilder strQuery = new StringBuilder("http://socurator.appspot.com/gp");
		strQuery.append("?action=makenew&");
		strQuery.append("title=").append(strTitle).append("&");
		strQuery.append("trigger_userid=").append(strUserID).append("&");
		strQuery.append("description=").append(strDescription).append("&");
		strQuery.append("lprice=").append(strLowPrice).append("&");
		strQuery.append("photo_url=").append(strImageURL);

		try {
			queryURL = new URL(strQuery.toString());
			
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(queryURL.openStream());
			
			strKey = doc.getElementsByTagName("gp_key").item(0).getChildNodes().item(0).getNodeValue().trim();
			
		} catch (MalformedURLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		} catch (ParserConfigurationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		} catch (SAXException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast t = Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT);
			t.show();
		}
		
		return strKey;
	}
	
	private ArrayList<NaverSearchResult> searchNaver(String query){
		ArrayList<NaverSearchResult> retItems = new ArrayList<NaverSearchResult>();
		
		NaverSearchResult result;
		URL queryURL=null;
		StringBuilder strQuery = new StringBuilder("http://openapi.naver.com/search");
		strQuery.append("?key=3ed2479fed5134318514a00d89098ff1&");
		strQuery.append("target=shop&");
		strQuery.append("query=").append(query);
		
		try {
			queryURL = new URL(strQuery.toString());
			
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(queryURL.openStream());
			
			Element root = doc.getDocumentElement();
			NodeList itemList = root.getElementsByTagName("item");
			for (int i = 0; i < itemList.getLength(); i++) {
				result = new NaverSearchResult();
				
				result.photo_url = itemList.item(i).getChildNodes().item(2).getChildNodes().item(0).getNodeValue();
				result.low_price = itemList.item(i).getChildNodes().item(3).getChildNodes().item(0).getNodeValue();
				retItems.add(result);
            }	
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return retItems;
	}
}
